/**
 * @description parse elem html
 * @author wangfupeng
 */

import { DOMElement } from '../dom';
import { IDomEditor, SlateDescendant, SlateElement } from '@wangeditor/editor';
import { MentionElement } from '../custom-types';

function parseHtml(elem: DOMElement, children: SlateDescendant[], editor: IDomEditor): SlateElement {
  // elem HTML 结构 <a data-w-e-type="mention" data-w-e-is-void data-w-e-is-inline data-value="张三" data-href=""  data-type="" data-target="" data-info="xxx">@张三</a>

  const value = elem.getAttribute('data-value') || '';
  const hrefInfo = decodeURIComponent(elem.getAttribute('data-href') || '');
  const typeLink = elem.getAttribute('data-type') || '';
  const target = elem.getAttribute('data-target') || '';
  let info: any;
  try {
    info = JSON.parse(hrefInfo);
  } catch (ex) {
    info = hrefInfo;
  }

  return {
    type: 'mention',
    value,
    info,
    url: hrefInfo,
    typeLink,
    target,
    children: [{ text: value}], // void node 必须有一个空白 text
  } as MentionElement;
}

const parseHtmlConf = {
  selector: 'a[data-w-e-type="mention"]',
  parseElemHtml: parseHtml,
};

export default parseHtmlConf;
